package com.gzrhhscd.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gzrhhscd.Pojo.Result;
import com.gzrhhscd.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        //1.get url
        String url=request.getRequestURI();
        log.info("请求的URL：{}",url);
        //2.if login let go
        if (url.contains("login")){
            log.info("登录操作，放行……");
//            filterChain.doFilter(request,response);
            return true;
        }
        //3.get the token
        String jwt=request.getHeader("token");
        //4.if jwt is null or doesn't exit , return NOT LOGIN
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头taken为空，返回未登录信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //5.parse jwt  if illegal return Not login
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {

            log.info("解析令牌失败，返回未登录错误信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //6.解析成功，放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("afterCompletion");
    }

}
